package com.hilaver.dzmis.web.servlet.basicinformation;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hilaver.dzmis.Constants;
import com.hilaver.dzmis.basicinfo.BiFactory;
import com.hilaver.dzmis.service.AbstractBaseService;
import com.hilaver.dzmis.util.StringUtils;
import com.hilaver.dzmis.web.servlet.AbstractBaseServlet;

public class BiFactoryServlet extends AbstractBaseServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public BiFactoryServlet(){
		this.fullName = BiFactory.class.getName();
		this.simpleName = BiFactory.class.getSimpleName();
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		try {
			writer.write(execute(request));
		} catch (Exception e) {
			writer.print(e.getMessage());
			e.printStackTrace();
		}
		writer.close();
	}

	protected String execute(HttpServletRequest request) throws Exception {
		this.setAction(request);

		Object serviceObj = this.getService();
		Method method = null;
		String rtn = "";
		Locale locale = (Locale) request.getSession().getAttribute(
				Constants.SESSION_LOCALE);
		
		method = serviceObj.getClass().getMethod("setLocale",
				new Class[] { Locale.class});
		method.invoke(serviceObj, new Object[] { locale });
		super.setAcUser(request, (AbstractBaseService)serviceObj);
		switch (this.action) {
		case ACTION_GET_ALL_PAGINATION_FILTER: // "getAllPagination filter"
			this.setPaginationParam(request);
			this.setFilterParam(request);
			String ctFactoryType = (String)this.getValue(request, "ctFactoryType");
			List<String> filtersList = new ArrayList<String>();;
			if(this.filters != null){
				for (int i = 0; i < this.filters.length; i++) {
					filtersList.add(this.filters[i]);
				}
			}
			if(!StringUtils.isEmpty(ctFactoryType)){
				filtersList.add("ctFactoryType=" + ctFactoryType);
			}
			method = serviceObj.getClass().getMethod(
					"getAllPagination",
					new Class[] { int.class, String.class, String.class,
							String[].class });// int page, String sort, String
			// order
			rtn = (String) method.invoke(serviceObj, new Object[] { this.page,
					this.sort, this.dir, (String[])filtersList.toArray(new String[0]) });
			break;
		default:
			rtn = super.execute(request);
		}

		return rtn;
	}

}
